package cn.lzg.client;

import java.net.InetSocketAddress;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import cn.lzg.common.core.codec.RequestEncoder;
import cn.lzg.common.core.codec.ResponseDecoder;
import cn.lzg.common.core.model.Request;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

@Component
public class Client {
	/**
	 * 服务器类
	 */
	Bootstrap bootstrap = new Bootstrap();

	/**
	 * 会话
	 */
	private Channel channel;

	/**
	 * 线程池
	 */
	private EventLoopGroup workerGroup = new NioEventLoopGroup();

	/**
	 * 启动
	 */
	@PostConstruct
	public void init() {
		bootstrap.group(workerGroup).channel(NioSocketChannel.class)
				.handler(new ChannelInitializer<SocketChannel>() {

					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new ResponseDecoder());
						ch.pipeline().addLast(new RequestEncoder());
						/**
						 * 消息handler
						 */
						ch.pipeline().addLast(new ClientHandler());
					}
				});
	}

	/**
	 * 连接服务器
	 * 
	 * @throws InterruptedException
	 */
	public void connect() throws InterruptedException {
		ChannelFuture connect = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8899));
		connect.sync();
		channel = connect.channel();
	}

	/**
	 * 关闭
	 */
	public void shutdown() {
		workerGroup.shutdownGracefully();
	}

	/**
	 * 获取会话
	 * 
	 * @return
	 */
	public Channel getChannel() {
		return this.channel;
	}

	/**
	 * 发送消息
	 * 
	 * @param request
	 * @throws InterruptedException
	 */
	public void sendMessage(Request request) throws InterruptedException {
		System.out.println("sendMessage");
		if (channel == null || !channel.isActive()) {
			System.out.println("connect");
			connect();
		}
		System.out.println("write");
		channel.writeAndFlush(request);
	}
}
